package com.example.mybatispdemo;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName StopWatchAspect
 * @Author ljp
 * @Date 2022/11/1 20:28
 */
@Aspect
@Component
public class StopWatchAspect {


    public Map<String, AopInfo> getHashMap() {
        return hashMap;
    }

    final Map<String,AopInfo> hashMap = Collections.synchronizedMap(new HashMap<>());


    @Pointcut("execution(* com.example.mybatispdemo.store.controller.*.*(..))")
    public void pt(){};
    @Around("pt()")
    public void aroundPointcut(ProceedingJoinPoint joinPoint) {
        long t1 = Calendar.getInstance().getTimeInMillis();
        String methodSig = joinPoint.getSignature().toString();
        AopInfo aopInfo = this.hashMap.get(methodSig)==null? new AopInfo():hashMap.get(methodSig);
        try {
            joinPoint.proceed();
            long t2 = Calendar.getInstance().getTimeInMillis();
            //相应时间
            long runTime = t2-t1;
            // 是否为最大相应时间
            if(runTime > aopInfo.getMaxRunTime()){
                aopInfo.setMaxRunTime(runTime);
            }
            //是否为最短相应时间
            if(runTime < aopInfo.getMinRunTime()){
                aopInfo.setMinRunTime(runTime);
            }
            // 更新平均响应时间
            int callNum = aopInfo.getCallNum();
            long times = (long) callNum * aopInfo.getCallNum()+t2;
            callNum+=1;
            aopInfo.setAverageRunTime(times/callNum);
            // 相应次数+1
            aopInfo.setCallNum(callNum);
            hashMap.put(methodSig,aopInfo);
        } catch (Throwable e) {
            // 抛出异常＋1
            aopInfo.setExceptionNum(aopInfo.getExceptionNum()+1);
            hashMap.put(methodSig,aopInfo);
        }
    }
}
